package cn.kgc.ssm.web.aspects;

import cn.hutool.json.JSONUtil;
import cn.kgc.ssm.web.annotations.Logs;
import cn.kgc.ssm.web.entity.LogInfo;
import cn.kgc.ssm.web.entity.User;
import cn.kgc.ssm.web.service.LogInfoService;
import cn.kgc.ssm.web.utils.IpUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author 课工场
 * @date 2024/8/5
 * @description   日志切面类
 */
@Component
@Aspect
public class LogsAspects {

    @Autowired
    private LogInfoService logInfoService;

    @Pointcut("@annotation(cn.kgc.ssm.web.annotations.Logs)")
    public  void  point(){}

    // 环绕通知
    @Around("point()")
    public Object  LogsAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {


        // 耗时
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        long timeConsuming = end-start;

        // 参数
        Object[] args = joinPoint.getArgs();
        String jsonArgs = JSONUtil.toJsonStr(args);



        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        Logs annotation = method.getAnnotation(Logs.class);

        // 操作   add  insert  delete
        String operation = annotation.operation().getOperation();
        // 模块
        String model = annotation.model();



        // 操作人    request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        User user = (User) request.getSession().getAttribute("user");
        String username = user.getUsername();

        // IP
        String ip = IpUtil.getIp(request);
        // 接口
        String requestURI = request.getRequestURI();



        LogInfo logInfo = new LogInfo();
        logInfo.setTimeConsuming(timeConsuming);
        logInfo.setUsername(username);
        logInfo.setIp(ip);
        logInfo.setUrl(requestURI);
        logInfo.setParams(jsonArgs);
        logInfo.setModel(model);
        logInfo.setDescription(operation);
        // TODO  添加日志信息   logInfoService

        logInfoService.addLogsInfo(logInfo);

        return proceed;
    }


}

